﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using VoteUphold;
using MSScriptControl;

namespace _12306
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private TrainUrl trainUrl;
        private HttpClient httpClient;
        private static ScriptControlClass scriptControlClass;
        private void FrmMain_Load(object sender, EventArgs e)
        {
            Init();
            Init2();
            //this.dgvResult.title.TitleHeader = new string[] { "1|三年绩二班学生成绩单|3" };   
            //this.dgvResult.ti
        }
        /// <summary>
        /// 相关 初始化
        /// </summary>
        private void Init()
        {
            this.Text = "查询";
            this.tsslblUpdateTime.Text = "";
            this.tsslblTrainInfo.Text = "";
            this.ckbZT.Tag = "Z";
            this.ckbTK.Tag = "T";
            this.ckbDC.Tag = "DC";
            this.ckbKS.Tag = "K";
            this.ckbAll.Tag = "value_ckball";
            this.ckbLK.Tag = "LK";
            this.ckbPKE.Tag = "PKE";
            this.ckbPK.Tag = "PK";

            this.rdoAll.Tag = "1";
            this.rdoTransience.Tag = "6";
            this.rdoStartEnd.Tag = "4";
            this.rdoStart.Tag = "3";
            this.rdoEnd.Tag = "9";
            this.ckbAll.Checked = true;
            this.rdoAll.Checked = true;
            trainUrl = new TrainUrl()
            {
                AdressVoteShow = "http://dynamic.12306.cn/TrainQuery/leftTicketByStation.jsp",
                AdressVoteSend = "http://dynamic.12306.cn/TrainQuery/iframeLeftTicketByStation.jsp"
            };
            httpClient = new HttpClient(new Uri(trainUrl.AdressVoteShow));
            scriptControlClass = new ScriptControlClass();
            scriptControlClass.Language = "javascript";
            //加入Microsoft.JScript与Microsoft.Vsa
            //sc.Eval();
            string getPwdStrFunction = @"
            function getPwdStrFunction(str, pwd){
            var prand = '';
            for(var i=0; i<pwd.length; i++) 
            {
               prand += pwd.charCodeAt(i).toString();
            }
            var sPos = Math.floor(prand.length / 5);
            var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5),10);
            var incr = Math.ceil(pwd.length / 2);
            var modu = Math.pow(2, 31) - 1;
            var salt = Math.round(Math.random() * 1000000000) % 100000000;
            prand += salt;
            prand = (mult * prand.length + incr) % modu;
            var enc_chr = '';
            var enc_str = '';
            for(var i=0; i<str.length; i++)
            {
               enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));

               if(enc_chr < 16) 
               {
                enc_str += '0'+ enc_chr.toString(16);
               } 
               else 
                enc_str += enc_chr.toString(16);

               prand = (mult * prand + incr) % modu;
            }
            salt = salt.toString(16);
            while(salt.length < 8)salt = '0' + salt;
               enc_str += salt;
            return enc_str;
            }
            ";
            scriptControlClass.AddCode(getPwdStrFunction);

        }

        //dgv的相关设置
        /// <summary>
        /// dgv的相关设置
        /// </summary>
        private void Init2()
        {
            this.Column1.HeaderText = "序号";
            this.Column2.HeaderText = "车次"; this.Column2.Width = 120;
            this.Column3.HeaderText = "发站"; this.Column3.Width = 60;
            this.Column4.HeaderText = "到站"; this.Column4.Width = 60;
            this.Column5.HeaderText = "发时"; this.Column5.Width = 60;
            this.Column6.HeaderText = "到时"; this.Column6.Width = 60;
            this.Column7.HeaderText = "历时"; this.Column7.Width = 60;
            this.Column8.HeaderText = "硬座"; this.Column8.Width = 60;
            this.Column9.HeaderText = "软座"; this.Column9.Width = 60;
            this.Column10.HeaderText = "硬卧"; this.Column10.Width = 60;
            this.Column11.HeaderText = "软卧"; this.Column11.Width = 60;
            this.Column12.HeaderText = "特等座"; this.Column12.Width = 70;
            this.Column13.HeaderText = "一等座"; this.Column13.Width = 70;
            this.Column14.HeaderText = "二等座"; this.Column14.Width = 70;
            this.Column15.HeaderText = "高级软卧"; this.Column15.Width = 80;
            this.Column16.HeaderText = "无座"; this.Column16.Width = 60;
            this.Column17.HeaderText = "等级"; this.Column17.Width = 60;

            this.Column1.DataPropertyName = "序号";
            this.Column2.DataPropertyName = "车次";
            this.Column3.DataPropertyName = "发站";
            this.Column4.DataPropertyName = "到站";
            this.Column5.DataPropertyName = "发时";
            this.Column6.DataPropertyName = "到时";
            this.Column7.DataPropertyName = "历时";
            this.Column8.DataPropertyName = "硬座";
            this.Column9.DataPropertyName = "软座";
            this.Column10.DataPropertyName = "硬卧";
            this.Column11.DataPropertyName = "软卧";
            this.Column12.DataPropertyName = "特等座";
            this.Column13.DataPropertyName = "一等座";
            this.Column14.DataPropertyName = "二等座";
            this.Column15.DataPropertyName = "高级软卧";
            this.Column16.DataPropertyName = "无座";
            this.Column17.DataPropertyName = "等级";


        }


        int top = 0;
        int left = 0;
        int height = 0;
        int width1 = 0;
        private void dgvResult_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            return;
            #region 重绘datagridview表头
            DataGridView dgv = (DataGridView)(sender);
            if (e.RowIndex == -1 && e.ColumnIndex%2==0)
            {

                //e.CellStyle.Font = new Font(dataGridView1.DefaultCellStyle.Font, FontStyle.Bold);
                //e.CellStyle.WrapMode = DataGridViewTriState.True;
                //if (e.ColumnIndex == 3)
                {
                    top = e.CellBounds.Top;
                    left = e.CellBounds.Left;
                    height = e.CellBounds.Height;
                    width1 = e.CellBounds.Width;
                }


                int width2 = this.dgvResult.Columns[4].Width;

                Rectangle rect = new Rectangle(left, top, width1 + width2, e.CellBounds.Height);
                using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
                {
                    //抹去原来的cell背景
                    //e.Graphics.FillRectangle(backColorBrush, rect);
                }

                using (Pen gridLinePen = new Pen(dgv.GridColor))
                {
                    e.Graphics.DrawLine(gridLinePen, left, top, left + width1 + width2, top);
                    e.Graphics.DrawLine(gridLinePen, left, top + height / 2, left + width1 + width2, top + height / 2);
                    e.Graphics.DrawLine(gridLinePen, left + width1, top + height / 2, left + width1, top + height);

                    //计算绘制字符串的位置
                    string columnValue = "year";
                    SizeF sf = e.Graphics.MeasureString(columnValue, e.CellStyle.Font);
                    float lstr = (width1 + width2 - sf.Width) / 2;
                    float rstr = (height / 2 - sf.Height) / 2;
                    //画出文本框

                    if (columnValue != "")
                    {
                        e.Graphics.DrawString(columnValue, e.CellStyle.Font,
                                                   new SolidBrush(e.CellStyle.ForeColor),
                                                     left + lstr,
                                                     top + rstr,
                                                     StringFormat.GenericDefault);
                    }


                    //计算绘制字符串的位置
                    columnValue = "局网台资产额";
                    sf = e.Graphics.MeasureString(columnValue, e.CellStyle.Font);
                    lstr = (width1 - sf.Width) / 2;
                    rstr = (height / 2 - sf.Height) / 2;
                    //画出文本框

                    if (columnValue != "")
                    {
                        e.Graphics.DrawString(columnValue, e.CellStyle.Font,
                                                   new SolidBrush(e.CellStyle.ForeColor),
                                                     left + lstr,
                                                     top + height / 2 + rstr,
                                                     StringFormat.GenericDefault);
                    }


                    //计算绘制字符串的位置
                    columnValue = "网络资产额";
                    sf = e.Graphics.MeasureString(columnValue, e.CellStyle.Font);
                    lstr = (width2 - sf.Width) / 2;
                    rstr = (height / 2 - sf.Height) / 2;
                    //画出文本框

                    if (columnValue != "")
                    {
                        e.Graphics.DrawString(columnValue, e.CellStyle.Font,
                                                   new SolidBrush(e.CellStyle.ForeColor),
                                                     left + width1 + lstr,
                                                     top + height / 2 + rstr,
                                                     StringFormat.GenericDefault);
                    }

                }
                e.Handled = true;


            }
            #endregion
        }

         


        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        //车 次 全部/全不选
        private void ckbAll_CheckedChanged(object sender, EventArgs e)
        {
            bool b = (sender as CheckBox).Checked;
            this.ckbZT.Checked = b;
            this.ckbTK.Checked = b;
            this.ckbDC.Checked = b;
            this.ckbKS.Checked = b;
            this.ckbLK.Checked = b;
            this.ckbPKE.Checked = b;
            this.ckbPK.Checked = b;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.btnSearch.Enabled = false;
            string s = "ictM=6674&fdl=fdl&lx=00&nyear3=2011&nyear3_new_value=true&nmonth3=01&nmonth3_new_value=true&nday3=31&nday3_new_value=false&startStation_ticketLeft=90d15d610559c337&startStation_ticketLeft_new_value=false&arriveStation_ticketLeft=53174e130345f396&arriveStation_ticketLeft_new_value=false&trainCode=&trainCode_new_value=true&rFlag=1&name_ckball=value_ckball&tFlagDC=DC&tFlagZ=Z&tFlagT=T&tFlagK=K&tFlagPK=PK&tFlagPKE=PKE&tFlagLK=LK";
            IDictionary<string, string> dictionary = new Dictionary<string, string>();
            PostData pd = new PostData(dictionary);
            DateTime dt = this.dtpBegin.Value;
            dictionary.Add("ictM", "6674");
            dictionary.Add("fdl", "fd1");
            dictionary.Add("lx", "00");
            dictionary.Add("nyear3", dt.Year.ToString());
            dictionary.Add("nyear3_new_value", "true");
            dictionary.Add("nmonth3", dt.ToString("MM"));
            dictionary.Add("nmonth3_new_value", "true");
            dictionary.Add("nday3", dt.ToString("dd"));
            dictionary.Add("nday3_new_value", "true");
            if (this.cboStart.Text=="")
            {
                this.cboStart.Text = "广州";
            }
            if (this.cboEnd.Text=="")
            {
                this.cboEnd.Text = "郑州";
            }
            object cityResult = scriptControlClass.Eval("getPwdStrFunction('" + this.cboStart.Text + "','liusheng')");
            dictionary.Add("startStation_ticketLeft", cityResult.ToString());//90d15d6100b7b0d3
            dictionary.Add("startStation_ticketLeft_new_value", "true");
            cityResult = scriptControlClass.Eval("getPwdStrFunction('" +this.cboEnd.Text  + "','liusheng')");
            dictionary.Add("arriveStation_ticketLeft",cityResult.ToString());
            dictionary.Add("arriveStation_ticketLeft_new_value", "true");
            dictionary.Add("trainCode", "");
            dictionary.Add("trainCode_new_value", "true");
            dictionary.Add("rFlag", "1");
            if (this.ckbAll.Checked) { dictionary.Add("name_ckball", this.ckbAll.Tag.ToString()); }
            if (this.ckbZT.Checked) { dictionary.Add("tFlagZ", this.ckbZT.Tag.ToString()); }
            if (this.ckbTK.Checked) { dictionary.Add("tFlagT", this.ckbTK.Tag.ToString()); }
            if (this.ckbDC.Checked) { dictionary.Add("tFlagDC", this.ckbDC.Tag.ToString()); }
            if (this.ckbKS.Checked) { dictionary.Add("tFlagK", this.ckbKS.Tag.ToString()); }
            if (this.ckbLK.Checked) { dictionary.Add("tFlagLK", this.ckbLK.Tag.ToString()); }
            if (this.ckbPKE.Checked) { dictionary.Add("tFlagPKE", this.ckbPKE.Tag.ToString()); }
            if (this.ckbPK.Checked) { dictionary.Add("tFlagPK", this.ckbPK.Tag.ToString()); }


            try
            {
                //<script>parent.document.getElementById("gxsj").innerHTML="余票信息每小时更新一次，本次信息更新时间为11:19。";parent.document.getElementById("ictM").value="6674"parent.mygrid.clearAll();</script>
                //"ictM=6674&fdl=fdl&lx=00&nyear3=2011&nyear3_new_value=true&nmonth3=01&nmonth3_new_value=true&nday3=31&nday3_new_value=false&startStation_ticketLeft=90d15d6100b7b0d3&startStation_ticketLeft_new_value=false&arriveStation_ticketLeft=5e7f5d610490230f&arriveStation_ticketLeft_new_value=false&trainCode=&trainCode_new_value=true&rFlag=1&name_ckball=value_ckball&tFlagDC=DC&tFlagZ=Z&tFlagT=T&tFlagK=K&tFlagPK=PK&tFlagPKE=PKE&tFlagLK=LK"
                string result = httpClient.PostData(trainUrl.AdressVoteSend, pd.ToString(), Encoding.UTF8, Encoding.UTF8);
                MatchData md = new MatchData("parent.document.getElementById\\(\"gxsj\"\\).innerHTML","\";",result);
                md.Match();
                md.Substring();
                this.tsslblTrainInfo.Text = md.Result;
                if (result.Contains("列车余票信息暂无"))
                {
                    this.tsslblTrainInfo.Text = "列车余票信息暂无。";
                }
                //parent.document.getElementById("gxsj").innerHTML="余票信息每小时更新一次，本次信息更新时间为14:07。";
                
                Match[] matchs = new MatchData(@"parent.mygrid.addRow\(" + MatchData.MATCH_STR, @"\);", result).Matches(RegexOptions.IgnoreCase);
                List<TrainInfo> listTrain = new List<TrainInfo>();
                foreach (var item in matchs)
                {
                    string value = item.Value;
                    string[] str = Regex.Match(value, "\"" + MatchData.MATCH_STR + "\"").Value.TrimStart('"').TrimEnd('"').Split(',');
                    if (str.Length >= 17)
                    {
                        TrainInfo ti = new TrainInfo();
                        ti.序号 = str[0];
                        int index=0;
                        if ((index=str[1].IndexOf('^')) > 0)
                        {
                            ti.车次 = str[1].Substring(0,index);
                        }
                        if ((index=str[2].IndexOf('^'))>0)
                        {
                            ti.发站 = str[2].Substring(0,index);
                        }
                        if ((index = str[3].IndexOf('^')) > 0)
                        {
                            ti.到站 = str[3].Substring(0, index);
                        }
                        ti.发时 = str[4];
                        ti.到时 = str[5];
                        ti.历时 = str[6];
                        ti.硬座 = str[7];
                        ti.软座 = str[8];
                        ti.硬卧 = str[9];
                        ti.软卧 = str[10];
                        ti.特等座 = str[11];
                        ti.一等座 = str[12];
                        ti.二等座 = str[13];
                        ti.高级软卧 = str[14];
                        ti.无座 = str[15];
                        ti.等级 = str[16];
                        ti.日期 = dt.ToString("yyyy年MM月dd日");
                        listTrain.Add(ti);
                    }
                }
                this.dgvResult.DataSource = listTrain;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.btnSearch.Enabled = true;
        }

        //发站 文本改变事件
        private void cboStart_TextChanged(object sender, EventArgs ev)
        {
            string start = this.cboStart.Text.Trim();
            if (start.Length <=1)
            {
                //return;
            }
            if (!Regex.IsMatch(start, "[a-zA-Z]"))
            {
               // return;
            }
            this.cboStart.Items.Clear();
            dynamic stationNames = GetStationName(start);
            if (stationNames != null)
            {
                foreach (var item in stationNames)
                {
                    //string elementValue= item.ElementValue;
                    string elementText = item.ElementText;
                    this.cboStart.Items.Add(elementText);
                }
            }
             
            //this.cboStart.
            //this.cboStart.Text = start;
            //this.cboStart.DropDownHeight = 500;
            //this.cboStart.DroppedDown = true;
            //this.cboStart.Focus();
            // System.Linq.Enumerable.WhereSelectEnumerableIterator<System.Xml.Linq.XElement,
            //  <>f__AnonymousType0<string,string>> action;


            //?method=getStationName&inputValue=SH&date=20110130&a_dhx_rSeed=1296374572378
        }
        private void cboEnd_TextChanged(object sender, EventArgs e)
        {
            string start = this.cboEnd.Text.Trim();
            if (start.Length <= 1)
            {
                return;
            }
            if (!Regex.IsMatch(start, "[a-zA-Z]"))
            {
                return;
            }
            string aa= CodingChange.CharacterToCoding("中国");
            this.cboEnd.Items.Clear();
            dynamic stationNames = GetStationName(start);
            if (stationNames != null)
            {
                foreach (var item in stationNames)
                {
                    //string elementValue= item.ElementValue;
                    string elementText = item.ElementText;
                    this.cboEnd.Items.Add(elementText);
                }
            }
        }

        private dynamic GetStationName(string start)
        {
            try
            {
                WebClient webClient = new WebClient();
                webClient.Encoding = Encoding.UTF8;
                string stationNameUrl = TrainUrl.GetStationNameUrl
                    + "?method=getStationName&inputValue=" + start.ToUpper()
                    + "&date=" + this.dtpBegin.Value.ToString("yyyyMMdd") + "&a_dhx_rSeed=123456789";
                string result = webClient.DownloadString(stationNameUrl);
                XDocument xd = XDocument.Load(new StringReader(result));
                var qurey = from e in xd.Descendants()
                            where e.NodeType == XmlNodeType.Element
                            && e.Name == XName.Get("option")
                            select new
                            {
                                ElementValue = e.Attribute(XName.Get("value")).Value,
                                ElementText = e.Value
                            };
                return qurey;
            }
            catch (Exception ex)
            {
            }
            return null;
        }

      

         

        
        
       

       

       

        

        
    }
}
